//
//  SKComposeTextView.swift
//  WeiboProjectYL
//
//  Created by yanli on 16/7/18.
//  Copyright © 2016年 mountainPassCell. All rights reserved.
//

import UIKit

// 让xib实时看到更改后的效果
@IBDesignable
class SKComposeTextView: UITextView {

    // 占位label
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "听说下雨天音乐跟辣条更配哟~"
        // 多行显示
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor()
        
        return label
    }()
    
    
    //外界设置占位文字
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    
    // 重写font
    override var font:UIFont? {
        didSet {
            placeHolderLabel.font = font
        }
    }
    
    // 重写text
    override var text: String? {
        didSet {
            placeHolderLabel.hidden = hasText()
        }
    }
    

    // 重写 构造函数
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        
    }

    // 使用xib 也可以
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    
    // 设置加载界面
    private func setupUI() {
        
        // 监听文字改变 (使用系统的通知,代理在外面被使用,不能再用)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        // 添加控件设置约束
        addSubview(placeHolderLabel)
        
        // 使用系统约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        //  设置宽度 -10（设置右边间距有问题）
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        
    }
    
    
    //  监听文字改变
    @objc private func textChange() {
        
        placeHolderLabel.hidden = self.hasText()
        
    }
    
    
    // 释放移除 通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}







